package com.haixiaoke.saas.menu.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.haixiaoke.saas.common.constant.UserConstants;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.department.service.IBizTenantMenuService;
import com.haixiaoke.saas.menu.domain.BizMenu;
import com.haixiaoke.saas.menu.mapper.BizMenuMapper;
import com.haixiaoke.saas.menu.service.IBizMenuService;
import com.haixiaoke.saas.common.Node;
import com.haixiaoke.saas.role.domain.BizRole;
import com.haixiaoke.saas.role.service.IBizRoleMenuService;
import com.haixiaoke.saas.role.service.IBizRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 企业端菜单权限Service业务层处理
 * 
 * @author panda
 * @date 2023-12-29
 */
@Service
public class BizMenuServiceImpl implements IBizMenuService {
    @Autowired
    private BizMenuMapper bizMenuMapper;
    @Autowired
    private IBizRoleService iBizRoleService;
    @Autowired
    private IBizRoleMenuService iBizRoleMenuService;
    @Autowired
    private IBizTenantMenuService iBizTenantMenuService;

    /**
     * 查询企业端菜单权限
     * 
     * @param menuId 企业端菜单权限主键
     * @return 企业端菜单权限
     */
    @Override
    public BizMenu selectBizMenuByMenuId(Long menuId) {
        return bizMenuMapper.selectBizMenuByMenuId(menuId);
    }

    /**
     * 查询企业端菜单权限列表
     *
     * @param bizMenu 企业端菜单权限
     * @param userId
     * @return 企业端菜单权限
     */
    @Override
    public List<BizMenu> selectBizMenuList(BizMenu bizMenu) {
        List<BizMenu> bizMenus = null;
        if (bizMenu.getUserId() == null) {
            bizMenus = bizMenuMapper.selectBizMenuList(bizMenu);
        } else {
            bizMenu.getParams().put("userId", bizMenu.getUserId());
            bizMenus = bizMenuMapper.selectBizMenuListByUserId(bizMenu);
        }
        return bizMenus;
    }

    /**
     * 新增企业端菜单权限
     * 
     * @param bizMenu 企业端菜单权限
     * @return 结果
     */
    @Override
    public int insertBizMenu(BizMenu bizMenu) {
        bizMenu.setCreateTime(DateUtils.getNowDate());
        return bizMenuMapper.insertBizMenu(bizMenu);
    }

    /**
     * 修改企业端菜单权限
     * 
     * @param bizMenu 企业端菜单权限
     * @return 结果
     */
    @Override
    public int updateBizMenu(BizMenu bizMenu) {
        bizMenu.setUpdateTime(DateUtils.getNowDate());
        return bizMenuMapper.updateBizMenu(bizMenu);
    }

    /**
     * 批量删除企业端菜单权限
     * 
     * @param menuIds 需要删除的企业端菜单权限主键
     * @return 结果
     */
    @Override
    public int deleteBizMenuByMenuIds(Long[] menuIds) {
        return bizMenuMapper.deleteBizMenuByMenuIds(menuIds);
    }

    /**
     * 删除企业端菜单权限信息
     * 
     * @param menuId 企业端菜单权限主键
     * @return 结果
     */
    @Override
    public int deleteBizMenuByMenuId(Long menuId) {
        //删除菜单关联数据
        iBizRoleMenuService.deleteBizRoleMenuByMenuId(menuId);
        iBizTenantMenuService.deleteBizTenantMenuByMenuId(menuId);
        //删除菜单
        return bizMenuMapper.deleteBizMenuByMenuId(menuId);
    }

    @Override
    public List<Node> buildMenuTreeSelect(BizMenu bizMenu) {
        List<BizMenu> menus = this.selectBizMenuList(bizMenu);
        List<BizMenu> bizMenus = buildMenuTree(menus);
        return bizMenus.stream().map(Node::new).collect(Collectors.toList());
    }

    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        BizRole role = iBizRoleService.selectBizRoleByRoleId(roleId);
        return bizMenuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    @Override
    public boolean checkMenuNameUnique(BizMenu bizMenu) {
        Long menuId = StringUtils.isNull(bizMenu.getMenuId()) ? -1L : bizMenu.getMenuId();
        BizMenu info = bizMenuMapper.checkMenuNameUnique(bizMenu.getMenuName(), bizMenu.getParentId());
        if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean hasChildByMenuId(Long menuId) {
        int result = bizMenuMapper.hasChildByMenuId(menuId);
        return result > 0;
    }

    @Override
    public boolean checkMenuExistRole(Long menuId) {
        int result = iBizRoleMenuService.checkMenuExistRole(menuId);
        return result > 0;
    }

    @Override
    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        List<String> perms = bizMenuMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = bizMenuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    public List<BizMenu> buildMenuTree(List<BizMenu> menus) {
        List<BizMenu> returnList = new ArrayList<BizMenu>();
        List<Long> tempList = menus.stream().map(BizMenu::getMenuId).collect(Collectors.toList());
        for (Iterator<BizMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            BizMenu menu = (BizMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<BizMenu> list, BizMenu t) {
        // 得到子节点列表
        List<BizMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BizMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<BizMenu> getChildList(List<BizMenu> list, BizMenu t) {
        List<BizMenu> tlist = new ArrayList<BizMenu>();
        Iterator<BizMenu> it = list.iterator();
        while (it.hasNext()) {
            BizMenu n = (BizMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<BizMenu> list, BizMenu t) {
        return !getChildList(list, t).isEmpty();
    }
}
